#include "bootpack.h"

void fifo32_init(struct FIFO32 *fifo, int size, int *buf, struct TASK *task)
/* 初始化FIFO缓冲区 */
{
    fifo->size = size;
    fifo->buf = buf;
    fifo->free = size; /* buffer size */
    fifo->flags = 0;
    fifo->w = 0; /* write */
    fifo->r = 0; /* read */
    fifo->task = task; /* wake task */
	return;
}

int fifo32_set(struct FIFO32 *fifo, int data)
/* 设置FIFO数据 */
{
    if (fifo->free == 0) {
        fifo->flags |= FLAGS_OVERFLOW;
        return -1;
    }
    fifo->buf[fifo->w] = data;
    fifo->w++;
    if (fifo->w == fifo->size) {
        fifo->w = 0;
    }
    fifo->free--;
    if (fifo->task != TASK_NULL)
    {
        if (fifo->task->flag != TASK_RUNNING)
            task_run(fifo->task, -1, 0);
    }
    return 0;
}

int fifo32_get(struct FIFO32 *fifo)
/* 从FIFO获取数据 */
{
    int data;
    if (fifo->free == fifo->size) {   /* empty */
        return -1;
    }
    data = fifo->buf[fifo->r];
    fifo->r++;
    if (fifo->r == fifo->size) {
        fifo->r = 0;
    }
    fifo->free++;
    return data;
}

int fifo32_status(struct FIFO32 *fifo)
/* 返回剩余数据 */
{
    return fifo->size - fifo->free;
}
